package com.skillworld.webapp.web.pages.rest.item;

import java.util.Calendar;
import java.util.Collections;
import java.util.Locale;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.bag.Bag;
import com.skillworld.webapp.model.bag.ItemRecord;
import com.skillworld.webapp.model.user.User;
import com.skillworld.webapp.model.userservice.UserService;
import com.skillworld.webapp.web.services.I18n;
import com.skillworld.webapp.web.util.DateHandler;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")

public class ViewBag
{ 
    
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @SuppressWarnings("unused")
    @Property
    private Bag bag;
    
    @SuppressWarnings("unused")
    @Property
    private ItemRecord entry;   // loop iterator

    @SuppressWarnings("unused")
    @Property
    private Locale locale;

    @Inject
    private UserService userService;
    
    @InjectService("I18n")
    private I18n i18n;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private Request request;

    void onPassivate()
    {
        return;
    }
        
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String langParam = request.getParameter("lang");
        
        try 
        {
            locale = i18n.selectLocale(langParam);
            User user = userService.findUserProfile(userSession.getUserId());
            bag = user.getBag();
            Collections.reverse(bag.getEntries());
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.APPLICATION_ERROR; }          
    }
}
